<?php


// Constants used almost everywhere.
define('_JEXEC', 1);
define('JPATH_BASE', dirname(__FILE__) . '/../..');
define('DS', DIRECTORY_SEPARATOR);


// Required to initialize the framework.
require_once JPATH_BASE . DS . 'includes' . DS . 'defines.php';
require_once JPATH_BASE . DS . 'includes' . DS . 'framework.php';
require_once JPATH_CONFIGURATION . DS . 'configuration.php';


// Read configuration values and connect to the database server.
$conf = JFactory::getConfig();
$conf->loadObject(new JConfig());
$db = JFactory::getDBO();


require_once dirname(__FILE__) . DS . 'helper.php';
$task = isset($_REQUEST['task']) ? $_REQUEST['task'] : '';
switch ($task)
{
	case 'ajax_post':
		ajax_post();
		break;
	case 'post':
		actions_post();
		break;
	default:
		ajax_default();
		break;
}


function ajax_default()
{
	header('Content-Type: text/javascript; charset=utf-8');
	header ("Cache-Control: no-cache, must-revalidate ");
	
	$since = JRequest::getInt('since', 0);
	$chatter = modChatterHelper::getLatestChatter($since);
	echo "{\nsuccess:true,";
	echo "\nlastLinePosted:$chatter->lastLinePosted,";
	echo "\nlines:[";
	foreach ($chatter->lines as $line)
	{
		echo "\n{nick:'", addslashes($line->nick)
			, '\',message:\'', addslashes($line->message)
			, "',color:'$line->color'},"
			;
	}
	echo "\n],\n}\n";
}


function ajax_post()
{
	jimport('joomla.filter.input');
	$filter = new JFilterInput();
	$nick = $filter->clean(JRequest::getString('nick', ''));
	$message = $filter->clean(JRequest::getString('message', ''));

	$success = modChatterHelper::postLine($nick, $message, $error);
	echo '{success:' . ($success ? 'true' : 'false') 
		. ',error:\'' . addslashes($error) . '\'}';
}


function actions_post()
{
	jimport('joomla.filter.input');
	$filter = new JFilterInput();
	$nick = $filter->clean($_REQUEST['nick']);
	$message = $filter->clean($_REQUEST['message']);

	modChatterHelper::postLine($nick, $message, $error);
	$url = get_referer();
	$mainframe = get_mainframe();
	$mainframe->redirect($url, $error);
}


function get_mainframe()
{
	global $mainframe;
	if (!isset($mainframe))
	{
		jimport('joomla.application.application');
		$mainframe = new JApplication(0);
		$mainframe->loadSession(JUtility::getHash($mainframe->getClientId()));
	}
	return $mainframe;
}


function get_referer()
{
	if (isset($_SERVER['HTTP_REFERER']))
		return $_SERVER['HTTP_REFERER'];
	else
		return '../../index.php';
}


?>
